﻿using System;

namespace AIFSContentManagementSystem.Criteria
{
    using Messages;

    public class CriteriaService : ICriteriaService
    {
        IRepositoryMap repositoryMap;

        public CriteriaService(IRepositoryMap RepositoryMap)
        {
            repositoryMap = RepositoryMap;
        }

        public GetCriterionResponse Process(GetCriterionRequest request)
        {
            GetCriterionResponse response = new GetCriterionResponse();
            
            if (!request.CriteriaId.HasValue)
                response.AddErrorMessage("Criteria id is required");

            if (response.HasError)
                return response;

            //Get the criterion
            ICriteriaRepository repository = repositoryMap.Get<ICriteriaRepository>();
            Criterion criterion = repository.GetCriterion(request.CriteriaId);
            
            if (criterion != null)
            {
                response.AddCriterion(criterion);
            }

            return response;
        }

        public SaveCriterionResponse Process(SaveCriterionRequest request)
        {
            SaveCriterionResponse response = new SaveCriterionResponse();

            if (request.Criterion == null)
                response.AddErrorMessage("Criterion is empty. Can not save.");

            if (response.HasError)
                return response;

            //Get the repository
            ICriteriaRepository repository = repositoryMap.Get<ICriteriaRepository>();
            repository.Save(request.Criterion);

            request.Criterion = repository.GetCriterion(request.Criterion.CriteriaId);

            response.AddCriterion(request.Criterion);

            return response;
        }
    }
}